package com.colabo.j2ee.web.oaf.orgnization.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.colabo.j2ee.web.core.context.ContextUtil;
import com.colabo.j2ee.web.core.exception.CommonException;
import com.colabo.j2ee.web.core.exception.ServiceException;
import com.colabo.j2ee.web.core.persistence.DateToStringUserType;
import com.colabo.j2ee.web.core.persistence.HqlWrapper;
import com.colabo.j2ee.web.core.pkgenerator.IPKGenerator;
import com.colabo.j2ee.web.core.servertime.IServerTime;
import com.colabo.j2ee.web.core.service.impl.DefaultServiceImpl;
import com.colabo.j2ee.web.core.util.DateTimeUtil;
import com.colabo.j2ee.web.core.util.PropertyUtil;
import com.colabo.j2ee.web.core.util.StringUtil;
import com.colabo.j2ee.web.core.vo.SessionUserHolder;
import com.colabo.j2ee.web.oaf.common.AppConstants;
import com.colabo.j2ee.web.oaf.monitorperspective.ILogDataService;
import com.colabo.j2ee.web.oaf.orgnization.IPositionService;
import com.colabo.j2ee.web.oaf.orgnization.IStaffService;
import com.colabo.j2ee.web.oaf.orgnization.model.IPDevolveVO;
import com.colabo.j2ee.web.oaf.orgnization.model.IPPositionVO;
import com.colabo.j2ee.web.oaf.orgnization.model.SCUserProfileVO;
import com.colabo.j2ee.web.oaf.orgnization.model.SCUnitProfileVO;
import com.colabo.j2ee.web.oaf.orgnization.util.ValidateResult;
import com.colabo.j2ee.web.oaf.security.AuthUtil;
import com.colabo.j2ee.web.oaf.security.ISecurityStrategyService;
import com.colabo.j2ee.web.oaf.security.model.SCUserSecurityVO;
import com.colabo.j2ee.web.oaf.vo.IPAuditLogVO;

public class StaffServiceImpl extends DefaultServiceImpl implements IStaffService {
	private Log logger = LogFactory.getLog(StaffServiceImpl.class);
	
	private static final String STAFF_SAVE_EXIST = "exist";
	private static final String STAFF_SAVE_SUCCESS = "true";
	private ISecurityStrategyService securityStrategyService = null;	
	private ILogDataService logDataService = null; 
	private IPKGenerator PKGenerator = null;
	//private static final String MODEL_Name = PropertyUtil.getPropertyByKey(AppConstants.MSG_INFO_APP_3003); 
	
	public IPKGenerator getPKGenerator() {
		return PKGenerator;
	}

	public void setPKGenerator(IPKGenerator pKGenerator) {
		PKGenerator = pKGenerator;
	}

	private List staffcodeList = new ArrayList();
	
	public SCUserProfileVO getStaffByStaffId(String staffid) throws ServiceException {
		if (staffid == null) {
			return null;
		}
		return (SCUserProfileVO) findByID_Hibernate_Get(SCUserProfileVO.class, staffid);
	}

	public List getAllStaffs(int offset, int pageSize) throws ServiceException {
		return find_iBatis("org.getAllStaffs", null, offset, pageSize);
	}

	public int getAllStaffCount() throws ServiceException {
		List countList = find_iBatis("org.getAllStaffCount", null);
		if (!countList.isEmpty()) {
			return ((Integer) countList.get(0)).intValue();
		}
		return 0;
	}

	public List getStaffsByUnit(SCUnitProfileVO unit) throws ServiceException {
		return getStaffsByUnit(unit, 0, 9999);
	}

	public List getStaffsByUnit(SCUnitProfileVO unit, int offset, int pageSize) throws ServiceException {
		if (unit != null) {
			return find_iBatis("org.getStaffsByUnit", unit, offset, pageSize);
		}
		return getAllStaffs(offset, pageSize);
	}

	public int getStaffCountByUnit(SCUnitProfileVO unit) throws ServiceException {
		if (unit != null) {
			List countList = find_iBatis("org.getStaffCountByUnit", unit);
			if (!countList.isEmpty()) {
				return ((Integer) countList.get(0)).intValue();
			}
			return 0;
		}
		return getAllStaffCount();
	}

	public List getStaffsByPosition(IPPositionVO position) throws ServiceException {
		return getStaffsByPosition(position, 0, 9999);
	}

	public List getStaffsByPosition(IPPositionVO position, int offset, int pageSize) throws ServiceException {
		if (position != null) {
			return find_iBatis("org.getStaffsByPosition", position, offset, pageSize);
		}
		return new ArrayList(0);
	}

	public int getStaffCountByPosition(IPPositionVO position) throws ServiceException {
		List countList = null;
		if (position != null) {
			countList = find_iBatis("org.getStaffCountByPosition", position);
		}
		if (countList != null && !countList.isEmpty()) {
			return ((Integer) countList.get(0)).intValue();
		}
		return 0;
	}
	
	public List queryStaffsByPosition(Map params, int offset, int pageSize) throws ServiceException {
		if (params != null) {
			return find_iBatis("org.queryStaffsByPosition", params, offset, pageSize);
		}
		return new ArrayList(0);
	}

	public int queryStaffCountByPosition(Map params) throws ServiceException {
		List countList = null;
		if (params != null) {
			countList = find_iBatis("org.queryStaffCountByPosition", params);
		}
		if (countList != null && !countList.isEmpty()) {
			return ((Integer) countList.get(0)).intValue();
		}
		return 0;
	}
	
	public List queryAllStaffsByPosition(Map params, int offset, int pageSize) throws ServiceException {
		if (params != null) {
			return find_iBatis("org.queryAllStaffsByPosition", params, offset, pageSize);
		}
		return new ArrayList(0);
	}

	public int queryAllStaffCountByPosition(Map params) throws ServiceException {
		List countList = null;
		if (params != null) {
			countList = find_iBatis("org.queryAllStaffCountByPosition", params);
		}
		if (countList != null && !countList.isEmpty()) {
			return ((Integer) countList.get(0)).intValue();
		}
		return 0;
	}

	public String batchCommit(List insertBeans, List updateBeans, List delBeans) throws ServiceException ,CommonException{
		int result = 0;
		
		List list = new ArrayList();
		if(insertBeans != null) {
			list.addAll(insertBeans);
		}
		if(updateBeans != null) {
			list.addAll(updateBeans);
		}
		if(!STAFF_SAVE_EXIST.equals(isDuplicate(list))) {
			return isDuplicate(list);
		}
		
		if (insertBeans != null) {
			
			for (Iterator it = insertBeans.iterator(); it.hasNext();) {									
				SCUserProfileVO userProfile = (SCUserProfileVO) it.next();
			    
				String ret = addStaff(userProfile);
				if(!ret.equals(userProfile.getLogicalKey())) {
					return ret;
				}
				result++;
			}
		}

		if (updateBeans != null) {
			
			for(int i=0; i<updateBeans.size(); i++) {
				SCUserProfileVO userProfile = (SCUserProfileVO) updateBeans.get(i);
				
				String ret = updateStaff(userProfile);
				if(!ret.equals(userProfile.getLogicalKey())) {
					return ret;
				}
				
				result++;
			}
		}

		if (delBeans != null) {
			for (Iterator it = delBeans.iterator(); it.hasNext();) {
				SCUserProfileVO userProfile = (SCUserProfileVO) it.next();	
				SCUserSecurityVO arcuser = findAuthUserByStaffid(userProfile.getLogicalKey());	
				delete(userProfile);
				if(arcuser != null){			    				    
					arcuser.setDelFlag(SCUserSecurityVO.DEL_FLAG_DELETED);
					update_Hibernate_Object(arcuser);						
				}
				update_iBatis("org.deleteDutyByStaffid", new Object[] { userProfile.getLogicalKey() });				
				result++;
			}
		}
		return STAFF_SAVE_SUCCESS;
	}

	private void delete(SCUserProfileVO userProfile) throws ServiceException ,CommonException{
		userProfile.setDelFlag(SCUserProfileVO.DEL_FLAG_DELETED);
		update(userProfile);
		SessionUserHolder suser = (SessionUserHolder)getBean("sessionUserHolder");
		logDataService.saveLog(IPAuditLogVO.BIZ_TYPE_ORG_MAINTAIN,  IPAuditLogVO.OP_CODE_DELETE, suser.getStaffId(), suser
				.getLoginIp(), PropertyUtil.getPropertyByKey(AppConstants.MSG_INFO_APP_3003) + IPAuditLogVO.SEPARATE + userProfile.getLogicalKey()+IPAuditLogVO.SEPARATE+userProfile.getRealName());
	}

	private int update(SCUserProfileVO staff) throws ServiceException ,CommonException {
		checkStaff(staff);		
		update_Hibernate_Object(staff);
		SessionUserHolder suser = (SessionUserHolder)getBean("sessionUserHolder");
		logDataService.saveLog(IPAuditLogVO.BIZ_TYPE_ORG_MAINTAIN,  IPAuditLogVO.OP_CODE_UPDATE, suser.getStaffId(), suser
				.getLoginIp(), PropertyUtil.getPropertyByKey(AppConstants.MSG_INFO_APP_3003) + IPAuditLogVO.SEPARATE +staff.getLogicalKey()+IPAuditLogVO.SEPARATE+staff.getRealName());
		return 1;
	}

	public String save(SCUserProfileVO userProfile) throws ServiceException, CommonException {
		checkStaff(userProfile);	
	    if(isExist(userProfile.getLogicalKey())){
	    	super.update_Hibernate_Object(userProfile);
        }
	   super.save_Hibernate_Object(userProfile);
	   return STAFF_SAVE_SUCCESS;
	}

	private void checkStaff(SCUserProfileVO userProfile) throws ServiceException,CommonException {
		IServerTime serverTime = (IServerTime) getBean(IServerTime.BEAN_ID);
		SCUnitProfileVO unitProfile = new SCUnitProfileVO();
		unitProfile.setLogicalKey("99999999999999999999999999999999");
		
		//如果没有主键，则生成对应主键并生成创建时间，否则修改最后修改时间
		if (userProfile.getLogicalKey() == null || "".equals(userProfile.getLogicalKey())) {
			userProfile.setLogicalKey(PKGenerator.getUUIDKey(userProfile));
			userProfile.setCreatorId("");
			userProfile.setCreatedTimestamp(serverTime.getServerDateTime());					
		}else{
			userProfile.setLastModifierId("");
			userProfile.setLastModifiedTimestamp(serverTime.getServerDateTime());
		}

		//如果没有所属机构，则挂接默认机构
		if (userProfile.getUnit() != null) {
			String unitid = userProfile.getUnit().getLogicalKey();
			if (unitid == null || "".equals(unitid)) {
				userProfile.setUnit(unitProfile);
			}
		}

		//如果没有所属机构，则挂接默认机构
		if (userProfile.getOffice() != null) {
			String unitid = userProfile.getOffice().getLogicalKey();
			if (unitid == null || "".equals(unitid)) {				
				userProfile.setOffice(unitProfile);
			}
		}

		//如果员工状态为空，则设置为默认状态
		if (userProfile.getStatus() == null) {
			userProfile.setStatus(SCUserProfileVO.STATUS_DEFAULT);
		}

		//如果员工删除状态为空，则设置为正常状态
		if (userProfile.getDelFlag() == null) {
			userProfile.setDelFlag(SCUserProfileVO.DEL_FLAG_NORMAL);
		}
	}

	public ValidateResult batchValidate(List insertBeans, List updateBeans, List delBeans) throws ServiceException {
		staffcodeList.clear();
		ValidateResult ret = new ValidateResult();

		return ret;
	}

	public List getStaffsByDefaultPositionInUnit(SCUnitProfileVO unitVo) throws ServiceException {
		IPositionService positionService = (IPositionService) getBean(IPositionService.BEAN_ID);
		IPPositionVO pos = positionService.getDefaultPosition(unitVo);
		return getStaffsByPosition(pos);
	}

	public int getStaffCountByOwnerUnit(SCUnitProfileVO unit) throws ServiceException {
		if (unit == null) {
			return 0;
		}
		List l = find_iBatis("org.getStaffCountByOwnerUnit", unit);
		if (l != null && l.size() > 0) {
			return ((Integer) l.get(0)).intValue();
		}
		return 0;
	}

	public List getStaffsByOwnerUnit(SCUnitProfileVO unit) throws ServiceException {
		return getStaffsByOwnerUnit(unit, 0, 9999);
	}

	public List getStaffsByOwnerUnit(SCUnitProfileVO unit, int offset, int pageSize) throws ServiceException {
		if (unit == null) {
			return new ArrayList();
		}
		return super.find_iBatis("org.getStaffsByOwnerUnit", unit, offset, pageSize);
	}

	public List getStaffByUnitSelectByPosition(SCUnitProfileVO unit, IPPositionVO position, int offset, int pageSize)
			throws ServiceException {
		Map m = new HashMap();
		if (unit != null) {
			m.put("unitid", unit.getLogicalKey());
		}
		if (position != null) {
			m.put("positionid", position.getPositionid());
		}
		return find_iBatis("org.getStaffsByUnitSelectByPosition", m, offset, pageSize);
	}

	public int getStaffCountByUnitSelectByPosition(SCUnitProfileVO unit, IPPositionVO position) throws ServiceException {
		return getStaffCountByUnit(unit);
	}
	
	public List queryStaffNotInPosition(Map params, int offset, int pageSize) throws ServiceException {
		// todo 验证查询参数合法性
		List list = find_iBatis("org.queryStaffNotInPosition", params, offset, pageSize);
		return list;
	}

	public int queryStaffCountNotInPosition(Map params) throws ServiceException {
		// todo 验证查询参数合法性
		List l = find_iBatis("org.queryStaffCountNotInPosition", params);
		if (l != null && !l.isEmpty()) {
			return ((Integer) l.get(0)).intValue();
		}
		return 0;
	}

	public List query(Map params, int offset, int pageSize) throws ServiceException {
		// todo 验证查询参数合法性
		List list = find_iBatis("org.queryStaff", params, offset, pageSize);
		return list;
	}

	public int queryCount(Map params) throws ServiceException {
		// todo 验证查询参数合法性
		List l = find_iBatis("org.queryStaffCount", params);
		if (l != null && !l.isEmpty()) {
			return ((Integer) l.get(0)).intValue();
		}
		return 0;
	}
	
	public List queryAll(Map params, int offset, int pageSize) throws ServiceException {
		
		return find_iBatis("org.queryAllStaff", params, offset, pageSize);
	}
	
	public int queryAllCount(Map params) throws ServiceException {
		
		List l = find_iBatis("org.queryAllStaffCount", params);
		if (l != null && !l.isEmpty()) {
			return ((Integer) l.get(0)).intValue();
		}
		return 0;
	}

	public SCUserSecurityVO findAuthUserByStaffid(String staffid) throws ServiceException{
		// TODO Auto-generated method stub
	    String sql = "from SCUserSecurityVO";    
	    HqlWrapper wrapper = new HqlWrapper();
	    wrapper.setCondition("staffid", HqlWrapper.EQUAL, staffid);
	    String[] propertyNames = StringUtil.listToStrArray(wrapper
	        .getPropertyNames());
	    String[] operators = StringUtil.listToStrArray(wrapper
	        .getOperators());
	    List valuesList = wrapper.getValues();
	    Object[] values = valuesList == null || valuesList.size() == 0 ? null
	        : valuesList.toArray();
	    String orderBy = null;
	    String groupBy = null;
	    String otherCause = null;
	    Object[] result = this.find_Hibernate_ComposedHQL(sql, propertyNames, operators,
	        values, 0, 999999, true, orderBy, groupBy, otherCause);
	    List l = (ArrayList)result[0];
		if (l.size()>0){
			SCUserSecurityVO authuser = (SCUserSecurityVO)l.get(0);
			return authuser;
		} 
		return null;		
	}
  	
	/**
	 * 根据应用判断是否存在人员
	 * @param unitcode
	 * @return
	 */
	public boolean isExist(String userProfileId) throws ServiceException {
	    String sql = "from SCUserProfileVO"; 
	    if(userProfileId == null || userProfileId.equals("")) {
	    	return false;
	    }
	    HqlWrapper wrapper = new HqlWrapper();
	    wrapper.setCondition("pk", HqlWrapper.EQUAL, userProfileId);
	    String[] propertyNames = StringUtil.listToStrArray(wrapper
	        .getPropertyNames());
	    String[] operators = StringUtil.listToStrArray(wrapper
	        .getOperators());
	    List valuesList = wrapper.getValues();
	    Object[] values = valuesList == null || valuesList.size() == 0 ? null
	        : valuesList.toArray();
	    String orderBy = null;
	    String groupBy = null;
	    String otherCause = null;
	    Object[] result = this.find_Hibernate_ComposedHQL(sql, propertyNames, operators,
	        values, 0, 999999, true, orderBy, groupBy, otherCause);
	    List l = (ArrayList)result[0];
		if (l.size()>0){				
			return true;
		} 
		return false;				
}
	public boolean isExist(String specifiedColumn, String specifiedValue) throws ServiceException {
	    String sql = "from SCUserProfileVO";
	    if(specifiedValue == null || specifiedValue.equals("")) {
	    	return false;
	    }
	    HqlWrapper wrapper = new HqlWrapper();
	    wrapper.setCondition(specifiedColumn, HqlWrapper.EQUAL, specifiedValue);
	    String[] propertyNames = StringUtil.listToStrArray(wrapper
	        .getPropertyNames());
	    String[] operators = StringUtil.listToStrArray(wrapper
	        .getOperators());
	    List valuesList = wrapper.getValues();
	    Object[] values = valuesList == null || valuesList.size() == 0 ? null
	        : valuesList.toArray();
	    String orderBy = null;
	    String groupBy = null;
	    String otherCause = null;
	    Object[] result = this.find_Hibernate_ComposedHQL(sql, propertyNames, operators,
	        values, 0, 999999, true, orderBy, groupBy, otherCause);
	    List l = (ArrayList)result[0];
		if (l.size()>0){				
			return true;
		} 
		return false;				
	}

	public boolean isExistPosition(String staffid,String positionid) throws ServiceException{
		// TODO Auto-generated method stub
		if("".equals(staffid) || staffid == null || 
				 "".equals(positionid) || positionid == null ){
			return false;
		}
		Map m = new HashMap();
		m.put("staffid", staffid);
		m.put("positionid", positionid);
		List l =  find_iBatis("org.isExistPosition", m);					
		if (l != null && !l.isEmpty()) {
			Integer i = (Integer)l.get(0);	
			if ( i.intValue() >0 ){
					return true;
				}		
		} 
		return false;		
	}

	public ISecurityStrategyService getSecurityStrategyService() {
		return securityStrategyService;
	}

	public void setSecurityStrategyService(
			ISecurityStrategyService securityStrategyService) {
		this.securityStrategyService = securityStrategyService;
	}

	/**
	 * 增加人员
	 * @param userProfile
	 * @return SCUserProfileVO对象的主键
	 * @throws ServiceException
	 */
	public String addStaff(SCUserProfileVO userProfile) throws ServiceException {
		getBean("sessionUserHolder");
		try {
			checkStaff(userProfile);
		} catch (CommonException e) {
			throw new ServiceException(e);
		}
		
	    IPKGenerator keyGen = (IPKGenerator) getBean(IPKGenerator.BEAN_ID);
		if( "".equals(userProfile.getLogicalKey()) ){				
			userProfile.setLogicalKey(keyGen.getUUIDKey());
		}

		if(userProfile.getDelFlag()==null){
			userProfile.setDelFlag(SCUserSecurityVO.DEL_FLAG_NORMAL);
		}
		
		save_Hibernate_Object(userProfile);		//添加员工
		
		SCUserSecurityVO userSecurity = new SCUserSecurityVO();
		userSecurity.setUserProfile(userProfile);
		userSecurity.setDelFlag(SCUserSecurityVO.DEL_FLAG_NORMAL);
		userSecurity.setLogicalKey(keyGen.getUUIDKey());
		
		//添加员工时，设置其密码为默认密码
		String passwd = securityStrategyService.getDefaultPasswd("");
		passwd = AuthUtil.encodePassword(passwd);
		userSecurity.setCredential(passwd);
		save_Hibernate_Object(userSecurity);		//添加用户
		
		//保存日志
		//FIXME 性能测试时：suser.getStaffId()总是为空，报错。
//		logDataService.saveLog(IPAuditLogVO.BIZ_TYPE_ORG_MAINTAIN,  IPAuditLogVO.OP_CODE_SAVE, suser.getStaffId(), suser
//				.getLoginIp(),  PropertyUtil.getPropertyByKey(AppConstants.MSG_INFO_APP_3003) + IPAuditLogVO.SEPARATE +vo.getStaffid() + IPAuditLogVO.SEPARATE+ vo.getStaffName() );
		return userProfile.getLogicalKey();
	}

	/**
	 * 修改人员信息
	 * @param voList  list里面存放的对象SCUserProfileVO
	 * @return
	 * @throws ServiceException
	 */
	public int updateStaffList(List voList) throws ServiceException {
		
		int rv = 0 ;
		
		if(null==voList){
			throw new ServiceException("The paramete is null");
		}
		
		SCUserProfileVO vo  = null;
		int count = voList.size();
		for(int i=0;i<count;i++){
			try{
				vo = (SCUserProfileVO)voList.get(i);
			}catch(Exception e){
				logger.error(e);
				vo = null;
			}
			if(vo==null){
				continue;
			}
			SessionUserHolder suser = (SessionUserHolder)getBean("sessionUserHolder");
			try {
				checkStaff(vo);
			} catch (CommonException e) {
				throw new ServiceException(e);
			}			
			update_Hibernate_Object(vo);	
			logDataService.saveLog(IPAuditLogVO.BIZ_TYPE_ORG_MAINTAIN,  IPAuditLogVO.OP_CODE_UPDATE, suser.getStaffId(), suser
					.getLoginIp(),  PropertyUtil.getPropertyByKey(AppConstants.MSG_INFO_APP_3003) + IPAuditLogVO.SEPARATE + vo.getLogicalKey() + IPAuditLogVO.SEPARATE+ vo.getRealName() );
			rv++;
		}
		
		return rv;
	}

	/**
	 * 删除人员信息，逻辑删除
	 * @param voList list里面存放的对象SCUserProfileVO
	 * @return
	 * @throws ServiceException
	 */
	public int deleteStaffList(List voList) throws ServiceException {
		if(null==voList){
			throw new ServiceException("The paramete is null");
		}
		
		int rv = 0;
		
		SCUserProfileVO vo  = null;
		int count = voList.size();
		for(int i=0;i<count;i++){
			try{
				vo = (SCUserProfileVO)voList.get(i);
			}catch(Exception e){
				logger.error(e);
				vo = null;
			}
			if(vo==null){
				continue;
			}
			SessionUserHolder suser = (SessionUserHolder)getBean("sessionUserHolder");
			try {
				checkStaff(vo);
			} catch (CommonException e) {
				throw new ServiceException(e);
			}
			vo.setDelFlag(SCUserSecurityVO.DEL_FLAG_DELETED);
			
			//将对应用户表记录也修改为删除状态
			SCUserSecurityVO avo = findAuthUserByStaffid(vo.getLogicalKey());
			
			update_Hibernate_Object(vo);
			
			if(avo != null){
				avo.setDelFlag(SCUserSecurityVO.DEL_FLAG_DELETED);
				update_Hibernate_Object(avo);
			}
			update_iBatis("org.deleteDutyByStaffid", new Object[] { vo.getLogicalKey() });	
			logDataService.saveLog(IPAuditLogVO.BIZ_TYPE_ORG_MAINTAIN,  IPAuditLogVO.OP_CODE_DELETE, suser.getStaffId(), suser
					.getLoginIp(),  PropertyUtil.getPropertyByKey(AppConstants.MSG_INFO_APP_3003) + IPAuditLogVO.SEPARATE + vo.getLogicalKey() + IPAuditLogVO.SEPARATE+ vo.getRealName() );
			rv++;
		}
		return rv;
	}

	public List queryStaffInfo(Map params, int offset, int pageSize)
			throws ServiceException {
		return find_iBatis("org.queryStaffInfo", params, offset, pageSize);
	}

	public int queryStaffInfoCount(Map params) throws ServiceException {
		List l = find_iBatis("org.queryStaffInfoCount", params);
		if (l != null && !l.isEmpty()) {
			return ((Integer) l.get(0)).intValue();
		}
		return 0;
	}

	public boolean delDutyByStaffidAndPosiid(String staffid, String positionid)
			throws ServiceException {
		if("".equals(staffid) || staffid == null || 
				 "".equals(positionid) || positionid == null ){
			return false;
		}
		Map m = new HashMap();
		m.put("staffid", staffid);
		m.put("positionid", positionid);
		int ret = update_iBatis("org.delDutyByStaffidAndPosiid", new Object[]{m} );		
		if( ret > 0 ){ 
			SessionUserHolder suser = (SessionUserHolder)getBean("sessionUserHolder");
			logDataService.saveLog(IPAuditLogVO.BIZ_TYPE_ORG_MAINTAIN,  IPAuditLogVO.OP_CODE_DELETE, suser.getStaffId(), suser
					.getLoginIp(),  PropertyUtil.getPropertyByKey(AppConstants.MSG_INFO_APP_3003) + IPAuditLogVO.SEPARATE + staffid+IPAuditLogVO.SEPARATE+positionid );
			return true;
		 }else{
			return false;
		}			
	}

	public long getMaxIndexNo() throws ServiceException {		
		List list = this.find_iBatis("org.getStaffMaxIndexNo", new HashMap());
		if(list != null && list.size()>0) {
			if(list.get(0) != null) {
				return new Long(list.get(0).toString()).longValue();
			}
		} 
		return 0;
	}

	public List listNoOrgStaff(Map params) throws ServiceException {		
		return this.find_iBatis("org.queryNoOrgStaffInfo", params);
	}

	public void updateStaffOrg(List staffIdList, String unitId ,String userId) throws ServiceException {		
		try {
			IServerTime serverTime = (IServerTime) ContextUtil.getBean(IServerTime.BEAN_ID);
			Date d = serverTime.getServerDateTime();
			String dateTime = DateTimeUtil.formatDateTime(d);
			if(staffIdList != null && unitId != null && userId != null) {
				
				StringBuffer sql = new StringBuffer("update wf_staff set UNITID='").append(unitId).append("'").append(",LASTMODIFIERID='").append(userId).append("'");
				sql.append(",LASTMODIFIEDTIME='").append(dateTime).append("'").append(" where STAFFID=?");
				for(int i=0; i < staffIdList.size(); i ++) {
					String staffid = (String)staffIdList.get(i);
					// Updated to Springframework 3.05
					// change String[] to Object[]
					// revised by Anthony on 2011 - 5 - 26
					Object[] param = {staffid};
					if(staffid != null) {
						this.getJdbcTemplate().update(sql.toString(), param);
						SessionUserHolder suser = (SessionUserHolder)getBean("sessionUserHolder");
						logDataService.saveLog(IPAuditLogVO.BIZ_TYPE_ORG_MAINTAIN,  IPAuditLogVO.OP_CODE_DELETE, suser.getStaffId(), suser
								.getLoginIp(), PropertyUtil.getPropertyByKey(AppConstants.MSG_INFO_APP_3003) + IPAuditLogVO.SEPARATE + staffid+IPAuditLogVO.SEPARATE+ unitId  );
					}
				}
			}
		} catch (CommonException e) {
			
			e.printStackTrace();
			throw new ServiceException(e);
		} catch (ServiceException e) {
			
			e.printStackTrace();
			throw e;
		}
		
	}

	public int batchCommitDevelope(List insertBeans, List updateBeans, List delBeans) throws ServiceException{
		int result = 0;
		IPKGenerator keyGen = (IPKGenerator) getBean(IPKGenerator.BEAN_ID);
		String dateNow = DateToStringUserType.formatDate(new Date(), DateToStringUserType.DATA_TO_STRING_FORMATE);	
		SessionUserHolder suser = (SessionUserHolder)getBean("sessionUserHolder");
		if (insertBeans != null) {
			for (Iterator it = insertBeans.iterator(); it.hasNext();) {									
				    IPDevolveVO vo = (IPDevolveVO) it.next();
				    vo.setPoid(keyGen.getUUIDKey(vo));
				    if("".equals(vo.getStatus()) || vo.getStatus() == null){
				    	vo.setStatus("1");
				    }
				    if("".equals(vo.getDelflag()) || vo.getDelflag() == null){
				    	vo.setDelflag(IPDevolveVO.DEL_FLAG_NORMAL);
				    }
				    if(vo.getStarttime() == null || "".equals(vo.getStarttime())){
				    	vo.setStarttime(dateNow.substring(0, 10));
				    }
				  
				    save_Hibernate_Object(vo);	
				    logDataService.saveLog(IPAuditLogVO.BIZ_TYPE_ORG_MAINTAIN,  IPAuditLogVO.OP_CODE_SAVE, suser.getStaffId(), suser
							.getLoginIp(), PropertyUtil.getPropertyByKey(AppConstants.MSG_INFO_APP_3003) + IPAuditLogVO.SEPARATE 
							+ vo.getFromstaffid()+IPAuditLogVO.SEPARATE+vo.getTostaffid() + PropertyUtil.getPropertyByKey(AppConstants.MSG_INFO_APP_3007) );
					result++;
				} 				
		}
		
		if (updateBeans != null) {
			for (Iterator it = updateBeans.iterator(); it.hasNext();) {
				 IPDevolveVO vo = (IPDevolveVO) it.next();
				 if(vo.getStatus() == null || "".equals(vo.getStatus())){
					 vo.setStatus("1");
				 }
				 if(vo.getDelflag() == null || "".equals(vo.getDelflag())){
					 vo.setDelflag(IPDevolveVO.DEL_FLAG_NORMAL);
				 }				 
				 update_Hibernate_Object(vo);
				 logDataService.saveLog(IPAuditLogVO.BIZ_TYPE_ORG_MAINTAIN,  IPAuditLogVO.OP_CODE_UPDATE, suser.getStaffId(), suser
							.getLoginIp(),  PropertyUtil.getPropertyByKey(AppConstants.MSG_INFO_APP_3003) + IPAuditLogVO.SEPARATE +vo.getFromstaffid()+IPAuditLogVO.SEPARATE+vo.getTostaffid() + PropertyUtil.getPropertyByKey(AppConstants.MSG_INFO_APP_3007) );
				 result++;
			}
		}
		
		if (delBeans != null) {
			for (Iterator it = delBeans.iterator(); it.hasNext();) {
				 IPDevolveVO vo = (IPDevolveVO) it.next();				 
				 vo.setDelflag(IPDevolveVO.DEL_FLAG_DELETED);   
				 vo.setStatus("0");				
				 update_Hibernate_Object(vo);
				 logDataService.saveLog(IPAuditLogVO.BIZ_TYPE_ORG_MAINTAIN,  IPAuditLogVO.OP_CODE_DELETE, suser.getStaffId(), suser
							.getLoginIp(),  PropertyUtil.getPropertyByKey(AppConstants.MSG_INFO_APP_3003) + IPAuditLogVO.SEPARATE + vo.getFromstaffid()+IPAuditLogVO.SEPARATE+vo.getTostaffid() + PropertyUtil.getPropertyByKey(AppConstants.MSG_INFO_APP_3007) );
				 result++;
			}
		}
		return result;
	}

	public List queryDevelope(String staffid) throws ServiceException {
		return find_iBatis("org.queryDevelope", staffid);
	}

	private List getStaffByCol(String colName, String colValue) throws ServiceException {
		
		String sql = "from SCUserProfileVO";
	    if(colValue == null || colValue.equals("")) {
	    	return new ArrayList();
	    }
	    HqlWrapper wrapper = new HqlWrapper();
	    wrapper.setCondition(colName, HqlWrapper.EQUAL, colValue);
	    String[] propertyNames = StringUtil.listToStrArray(wrapper
	        .getPropertyNames());
	    String[] operators = StringUtil.listToStrArray(wrapper
	        .getOperators());
	    List valuesList = wrapper.getValues();
	    Object[] values = valuesList == null || valuesList.size() == 0 ? null
	        : valuesList.toArray();
	    String orderBy = null;
	    String groupBy = null;
	    String otherCause = null;
	    Object[] result = this.find_Hibernate_ComposedHQL(sql, propertyNames, operators,
	        values, 0, 999999, true, orderBy, groupBy, otherCause);
	    
	    return (List) result[0];
	}
	
	/**
	 * 批量增删改时，判断用户名、NotesId、人力资源ID是否有重复
	 * 
	 * @param staffList
	 * @return
	 * @throws ServiceException
	 */
	private String isDuplicate(List staffList) throws ServiceException {
		
		Map staffCodeMap = new HashMap();
		Map notesIdMap = new HashMap();
		Map hrIdMap = new HashMap();
		
		for(int i=0; i<staffList.size(); i++) {
			
			SCUserProfileVO staff = (SCUserProfileVO) staffList.get(i);
			
			if(staff.getLoginId() != null) {
				if(staffCodeMap.get(staff.getLoginId()) == null) {
					staffCodeMap.put(staff.getLoginId(), staff);
				} else {
					return "0" + staff.getLoginId();
				}
			}
			
			if(staff.getAliasName() != null) {
				if(notesIdMap.get(staff.getAliasName()) == null) {
					notesIdMap.put(staff.getAliasName(), staff);
				} else {
					return "2" + staff.getAliasName();
				}
			}
			
			if(staff.getHrId() != null) {
				if(hrIdMap.get(staff.getHrId()) == null) {
					hrIdMap.put(staff.getHrId(), staff);
				} else {
					return "3" + staff.getHrId();
				}
			}
		}
		
		return STAFF_SAVE_EXIST;
	}

	/**
	 * 更新Staff并检验用户名、NotesId、人力资源ID是否唯一
	 * 
	 * @param userProfile
	 * @return
	 * @throws ServiceException
	 */
	private String updateStaff(SCUserProfileVO userProfile) throws ServiceException {
		
		SessionUserHolder suser = (SessionUserHolder)getBean("sessionUserHolder");
		try {
			checkStaff(userProfile);
		} catch (CommonException e) {
			throw new ServiceException(e);
		}
		
		//如果人员编码一致，但主键不一致，说明存在重复编码
		List list = getStaffByCol("LOGIN_ID", userProfile.getLoginId());
		if(list.size() > 0){
			for(int i=0; i<list.size(); i++) {
				SCUserProfileVO staff = (SCUserProfileVO) list.get(i);
				if(!staff.getLogicalKey().equals(userProfile.getLogicalKey())) {
					
					return userProfile.getLoginId();
				}
			}
        }
		
		//如果人员登陆名一致，但主键不一致，说明存在重复登陆名
		list = getStaffByCol("loginName", userProfile.getRealName());
		if(list.size() > 0){
			for(int i=0; i<list.size(); i++) {
				SCUserProfileVO staff = (SCUserProfileVO) list.get(i);
				if(!staff.getLogicalKey().equals(userProfile.getLogicalKey())) {
					
					return "1" + userProfile.getRealName();
				}
			}
        }
		
		//如果人员NotesID一致，但主键不一致，说明存在重复NotesID
		list = getStaffByCol("notesId", userProfile.getAliasName());
		if(list.size() > 0){
			for(int i=0; i<list.size(); i++) {
				SCUserProfileVO staff = (SCUserProfileVO) list.get(i);
				if(!staff.getLogicalKey().equals(userProfile.getLogicalKey())) {
					
					return "2" + userProfile.getAliasName();
				}
			}
        }
		
		//如果人员人力资源ID一致，但主键不一致，说明存在重复人力资源ID
		list = getStaffByCol("hrId", userProfile.getHrId());
		if(list.size() > 0){
			for(int i=0; i<list.size(); i++) {
				SCUserProfileVO staff = (SCUserProfileVO) list.get(i);
				if(!staff.getLogicalKey().equals(userProfile.getLogicalKey())) {
					
					return "3" + userProfile.getHrId();
				}
			}
        }
	    
		update_Hibernate_Object(userProfile);
		logDataService.saveLog(IPAuditLogVO.BIZ_TYPE_ORG_MAINTAIN,  IPAuditLogVO.OP_CODE_UPDATE, suser.getStaffId(), suser
				.getLoginIp(),  PropertyUtil.getPropertyByKey(AppConstants.MSG_INFO_APP_3003) + IPAuditLogVO.SEPARATE + userProfile.getLogicalKey() + IPAuditLogVO.SEPARATE+ userProfile.getRealName() );
		
		return userProfile.getLogicalKey();
	}
	
	public List queryBack(Map params, int offset, int pageSize) throws ServiceException {
		// todo 验证查询参数合法性
		List list = find_iBatis("org.queryBackStaff", params, offset, pageSize);
		return list;
	}
	
	public int queryBackCount(Map params) throws ServiceException {
		// todo 验证查询参数合法性
		List l = find_iBatis("org.queryBackStaffCount", params);
		if (l != null && !l.isEmpty()) {
			return ((Integer) l.get(0)).intValue();
		}
		return 0;
	}
	
	public List queryBackAll(Map params, int offset, int pageSize) throws ServiceException {
		
		return find_iBatis("org.queryAllBackStaff", params, offset, pageSize);
	}
	
	public int queryBackAllCount(Map params) throws ServiceException {
		
		List l = find_iBatis("org.queryAllBackStaffCount", params);
		if (l != null && !l.isEmpty()) {
			return ((Integer) l.get(0)).intValue();
		}
		return 0;
	}
	
	public String saveBackToStaff(List backBeans) throws ServiceException ,CommonException{
		int result = 0;
		
		if (backBeans != null) {
			for (Iterator it = backBeans.iterator(); it.hasNext();) {
				SCUserProfileVO userProfile = (SCUserProfileVO) it.next();	
				SCUserSecurityVO userSecurity = findAuthUserByStaffid(userProfile.getLogicalKey());				    				   				
				updateBackStaff(userProfile);
				
				//如果用户存在，则修改对应用户状态，如果用户不存在，则新增一个用户。
				if(userSecurity != null){
					userSecurity.setDelFlag(SCUserSecurityVO.DEL_FLAG_NORMAL);
					update_Hibernate_Object(userSecurity);						
				}else{
					userSecurity = new SCUserSecurityVO();
					userSecurity.setUserProfile(userProfile);
					userSecurity.setDelFlag(SCUserSecurityVO.DEL_FLAG_NORMAL);
					IPKGenerator keyGen = (IPKGenerator) getBean(IPKGenerator.BEAN_ID);
					userSecurity.setLogicalKey(keyGen.getUUIDKey());
					
					//添加员工时，设置其密码为默认密码
					String passwd = securityStrategyService.getDefaultPasswd("");
					passwd = AuthUtil.encodePassword(passwd);
					userSecurity.setCredential(passwd);
					save_Hibernate_Object(userSecurity);		//添加用户
				}
				update_iBatis("org.backDutyByStaffid", new Object[] { userProfile.getLogicalKey() });				
				result++;
			}
		}
		return STAFF_SAVE_SUCCESS;
	}
	
	public String saveFullDel(List delBeans) throws ServiceException ,CommonException{
		int result = 0;
		
		if (delBeans != null) {
			for (Iterator it = delBeans.iterator(); it.hasNext();) {
				SCUserProfileVO ips = (SCUserProfileVO) it.next();	
				update_iBatis("org.delFullDutyByStaffid", new Object[] { ips.getLogicalKey() });
				
				SCUserSecurityVO arcuser = findAuthUserByStaffid(ips.getLogicalKey());				    				    
				if(arcuser != null){
					delete_Hibernate_Object(arcuser);						
				}
				
				delFullStaff(ips);
												
				result++;
			}
		}
		return STAFF_SAVE_SUCCESS;
	}

	private void updateBackStaff(SCUserProfileVO ips) throws ServiceException,
			CommonException {
		ips.setDelFlag(SCUserSecurityVO.DEL_FLAG_NORMAL);
		checkStaff(ips);
		update_Hibernate_Object(ips);
		SessionUserHolder suser = (SessionUserHolder)getBean("sessionUserHolder");
		logDataService.saveLog(IPAuditLogVO.BIZ_TYPE_ORG_MAINTAIN,  IPAuditLogVO.OP_CODE_UPDATE, suser.getStaffId(), suser
				.getLoginIp(), PropertyUtil.getPropertyByKey(AppConstants.MSG_INFO_APP_3002) + IPAuditLogVO.SEPARATE + ips.getLogicalKey()+IPAuditLogVO.SEPARATE+ips.getRealName());
	}
	
	private void delFullStaff(SCUserProfileVO ips) throws ServiceException,
			CommonException {
		ips.setUnit(null);
		ips.setOffice(null);
		delete_Hibernate_Object(ips);
		SessionUserHolder suser = (SessionUserHolder)getBean("sessionUserHolder");
		logDataService.saveLog(IPAuditLogVO.BIZ_TYPE_ORG_MAINTAIN,  IPAuditLogVO.OP_CODE_DELETE, suser.getStaffId(), suser
					.getLoginIp(), PropertyUtil.getPropertyByKey(AppConstants.MSG_INFO_APP_3002) + IPAuditLogVO.SEPARATE + ips.getLogicalKey()+IPAuditLogVO.SEPARATE+ips.getRealName());
}
	
	public ILogDataService getLogDataService() {
		return logDataService;
	}

	public void setLogDataService(ILogDataService logDataService) {
		this.logDataService = logDataService;
	}		
}
